import type { Router, RouteRecordRaw } from 'vue-router'
import { useMenuStore } from '@/store/modules/menu'

import layout from '@/layout/index.vue'

const newRoutes: Array<RouteRecordRaw> = [
  {
    path: '/childOne',
    meta: {
      appName: 'childOne',
      url: 'http://localhost:9091',
    },
    component: layout,
    children: [
      {
        path: 'A',
        meta: {
          path: '/A',
        },
        component: () => import('@/microApp/index.vue'),
      },

      {
        path: 'B',
        meta: {
          path: '/B',
        },
        component: () => import('@/microApp/index.vue'),
      },
    ],
  },
  {
    path: '/childTwo',
    meta: {
      appName: 'childTwo',
      url: 'http://localhost:9092',
    },
    component: layout,
    children: [
      {
        path: 'A',
        component: () => import('@/microApp/index.vue'),
        meta: {
          path: '/A',
        },
      },
      {
        path: 'B',
        meta: {
          path: '/B',
        },
        component: () => import('@/microApp/index.vue'),
      },
    ],
  },
]

export const createRouterGuards = (router: Router) => {
  const { menuList } = storeToRefs(useMenuStore())

  router.beforeEach((to, from, next) => {
    if (!menuList.value || !menuList.value?.length) {
      useMenuStore().setMenu(newRoutes)
      newRoutes.forEach(route => {
        router.addRoute(route)
      })
      next({ ...to, replace: true })
      return
    } else {
      next()
      return
    }
  })
}
